﻿package com.thorqq.magictimer;

import com.thorqq.magictimer.download.DownloadProxy;
import com.thorqq.magictimer.util.Util;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

public class UmengUpdateManager implements UmengUpdateListener
{

    private final static int SHOW_QUERY_LATEST_VERSION_YES = 0;
    private final static int SHOW_QUERY_LATEST_VERSION_NO = 1;

    private Context mContext;
    private static UmengUpdateManager mInstance;
    private ProgressDialog mProgressQueryUpdate = null;
    private int mShowQueryProgressDlg = SHOW_QUERY_LATEST_VERSION_NO;

    static public UmengUpdateManager getIntance()
    {
        if (mInstance == null)
        {
            mInstance = new UmengUpdateManager(null);
        }
        return mInstance;
    }

    private UmengUpdateManager(Context context)
    {
        this.mContext = context;
    }

    /**
     * 检测软件更新
     */
    public void checkUpdateSilence(Context context)
    {
        this.mContext = context;
        mShowQueryProgressDlg = SHOW_QUERY_LATEST_VERSION_NO;
        checkUpdate();
    }

    public void checkUpdate(Context context)
    {
        this.mContext = context;
        mShowQueryProgressDlg = SHOW_QUERY_LATEST_VERSION_YES;
        checkUpdate();
    }

    public void checkUpdate()
    {
        Util.log("Check update");

        if (mShowQueryProgressDlg == SHOW_QUERY_LATEST_VERSION_YES)
        {
            mProgressQueryUpdate = ProgressDialog.show(mContext, null, "正在查询最新版本", true, false);
        }

        try
        {
            UmengUpdateAgent.setUpdateOnlyWifi(false);
            UmengUpdateAgent.update(mContext);
            UmengUpdateAgent.setUpdateAutoPopup(false);
            UmengUpdateAgent.setUpdateListener(this);

        } catch (Exception e)
        {
            Util.log_ex(e);
            return;
        }
    }

    /**
     * 显示无需更新对话框
     */
    private void showNoUpdateDialog()
    {
        // 构造对话框
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage("已经是最新版本，无需更新");
        builder.setPositiveButton("确定", new OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });

        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

//    private Handler p = new Handler()
//    {
//        public void handleMessage(Message paramMessage)
//        {
//            super.handleMessage(paramMessage);
//
//            onUpdateReturned(paramMessage.what, (UpdateResponse)paramMessage.obj);
//        }
//    };

    //对话框提示用户是立即下载还是稍后下载
    public void showUpdateDialogEx(final Context context, final UpdateResponse paramUpdateResponse)
    {
        try
        {
            String str = "";
            if (!com.umeng.common.b.l(context))
            {
                // （提示：非WIFI环境）
                str = context.getString(com.umeng.common.c.a(context).f("UMGprsCondition")) + "\n";
            }
            StringBuffer localStringBuffer = new StringBuffer();
            localStringBuffer.append(str);

            // 最近版本：
            localStringBuffer.append(context.getString(com.umeng.common.c.a(context).f(
                    "UMNewVersion")));
            localStringBuffer.append(paramUpdateResponse.version);
            localStringBuffer.append("\n");

            if (paramUpdateResponse.target_size != null)
            {
                // 新版本大小：
                localStringBuffer.append(context.getString(com.umeng.common.c.a(context).f(
                        "UMTargetSize")));
                localStringBuffer
                        .append(com.umeng.common.util.g.c(paramUpdateResponse.target_size));
                localStringBuffer.append("\n");

                if (!paramUpdateResponse.target_size.equals(paramUpdateResponse.size))
                {
                    // 更新包大小：
                    localStringBuffer.append(context.getString(com.umeng.common.c.a(context).f(
                            "UMUpdateSize")));

                    localStringBuffer.append(com.umeng.common.util.g.c(paramUpdateResponse.size));
                    localStringBuffer.append("\n");
                }
            }
            // 更新信息
            localStringBuffer.append(paramUpdateResponse.updateLog);

            // 显示立即更新、稍后更新的对话框
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(context);
            localBuilder.setTitle("有新版本更新");
            localBuilder.setMessage(localStringBuffer.toString());
            localBuilder.setPositiveButton("立即更新", new OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    DownloadProxy proxy = DownloadProxy.getInstance();
                    proxy.initDownloaderDirectly(paramUpdateResponse.path,
                            mContext.getString(R.string.app_name) + paramUpdateResponse.version + ".apk",
                            true);
                    
                    dialog.dismiss();
                }
            });
            localBuilder.setNegativeButton("稍后更新", new OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.dismiss();
                }
            });

            localBuilder.create().show();
        } catch (Exception e)
        {
            Util.log("Fail to create update dialog box");
            Util.log_ex(e);
        }
    }
    
    //处理是否有最新版本
    @Override
    public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo)
    {
        if (mProgressQueryUpdate != null)
        {
            mProgressQueryUpdate.dismiss();
        }

        if(updateInfo != null)
        {
            Util.log("updateInfo: " + updateInfo.version + "|" +
                    updateInfo.path + "|" +
                    updateInfo.proto_ver + "|" +   //协议版本
                    updateInfo.size + "|" +
                    updateInfo.target_size + "|" +
                    updateInfo.new_md5 + "|" +
                    updateInfo.patch_md5 + "|" +
                    updateInfo.updateLog + "|" +
                    updateInfo.delta
                    );
        }

        switch (updateStatus)
        {
        case UpdateStatus.Yes: // has update
            UmengUpdateManager.this.showUpdateDialogEx(mContext, updateInfo);
//            UmengUpdateAgent.showUpdateDialog(mContext, updateInfo);
            break;
        case UpdateStatus.No: // has no update
            if (mShowQueryProgressDlg == SHOW_QUERY_LATEST_VERSION_YES)
            {
                showNoUpdateDialog();
            }
            break;
        case UpdateStatus.NoneWifi: // none wifi
//            Toast.makeText(mContext, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
            break;
        case UpdateStatus.Timeout: // time out
//            Toast.makeText(mContext, "连接超时", Toast.LENGTH_SHORT).show();
            break;
        }
        
    }

}